<?php
require_once 'assets/tool/PHPExcel/PHPExcel.php';
require_once 'assets/tool/PHPExcel/PHPExcel/IOFactory.php';

class filesLogic
{
    //Define constance
    const ERROR_TEMP_FILE      = 9;
    const ERROR_EXTENSION_FILE = 10;

    //File extension
    const IMAGE_EXTENSIONS     = 'jpg,jpeg,gif,png';
    const DATA_EXTENSIONS      = 'csv,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';

    //Data File Format
    const DATA_FORMAT_DEFAULT = 0;
    const DATA_FORMAT_CUSTOM  = 1;

    //Init properties
    protected $properties;

    /** __construct ========================
     * @author TuanNguyen
     * @desc   set param of class to default
     *         use wizard of PHP
     * =====================================*/
    function __construct()
    {
        $this->properties = array();
    }

    /** __get =================================
     * @author TuanNguyen
     * @desc   get value of properties of class
     *         use wizard of PHP method
     * ========================================*/
    function __get($propety)
    {
        return $this->properties[$propety];        
    }

    /** __set =================================
     * @author TuanNguyen
     * @desc   set value of properties of class
     *         use wizard of PHP method
     * ========================================*/
    function __set($property, $value)
    {
        $this->properties[$property] = $value;
    }
    
    /** uploadFile =============================================
     * @author   TuanNguyen
     * @desc     loop all error entity in array
     *           set error messages in array of error message
     * @param    array $arr_errorEnts: array of error entity
     *           array $arr_errorMessage: array of error message
     * @return   string
     * =========================================================*/
    public static function uploadFile($arr_fileInput, $s_fileExtension)
    {
        if ( !empty($arr_fileInput['error']) ) {
            return $arr_fileInput['error'];
        }

        if ( empty($arr_fileInput['tmp_name']) || $arr_fileInput['tmp_name'] === 'none' ) {
            return self::ERROR_TEMP_FILE;
        }

        if ( $s_fileExtension !== null || $s_fileExtension != '' )
        {
            $arr_types = explode(',', $s_fileExtension);

            if ( $arr_types !== null && !in_array($arr_fileInput["type"], $arr_types) ) {
                return self::ERROR_EXTENSION_FILE;
            }
        }//End if

        $date_insert = new DateTime();
        $s_fileurl   = 'tempFiles/'.$date_insert->format('Ymd').$arr_fileInput["name"];

        move_uploaded_file($arr_fileInput["tmp_name"],$s_fileurl);

        return $s_fileurl;
    }//End uploadFile

    /** getDataFormExcel ======================================
     * @author   TuanNguyen
     * @desc     Read excel file form folder at server
     *           set all value of acvtive sheet into array
     * @param    string $s_URLFile
     * @return   array
     * =========================================================*/
    public static function getDataFromExcel($s_URLFile, $s_sheetName, $i_HeaderIndex, $arr_columnDefinition, $o_dataEntity)
    {
        $o_PHPExcel          = PHPExcel_IOFactory::load($s_URLFile);
        $arr_rowList         = $o_PHPExcel->getSheetByName($s_sheetName)->toArray(null,true,true,true);
        $arr_dataList        = array();
        $arr_HeaderIndexList = array();
        $i_totalRow          = count($arr_rowList);

        #Region Fetch excel column Index by column name
        //Loop columnName of table to get list of definition column name
        foreach ($arr_columnDefinition as $s_columnName => $arr_headerDefinition) {
            //Loop header row of excel to get column index in excel file of columnName in table
            foreach ( $arr_rowList[$i_HeaderIndex] as $s_excelColumnIndex => $s_HeaderValue )
            {
                $s_HeaderValue = strtolower(str_replace(' ', '', $s_HeaderValue));
                $s_HeaderValue = stringLogic::convertVNToAlphabet($s_HeaderValue);

                //if value exist in list of definition column name, set into array
                //with value is excel column Index
                //key is column name in  table
                if ( in_array($s_HeaderValue, $arr_headerDefinition) ) {
                    $arr_HeaderIndexList[$s_columnName] = $s_excelColumnIndex;
                }
            }//End foreach
        }//End foreach
        #EndRegion

        //If total row < header row index, return array
        if ( $i_totalRow <= $i_HeaderIndex ) {
            return $arr_dataList;
        }

        #Region Fetch excel column value by column name
        //loop row list of excel file
        for ( $i = $i_HeaderIndex + 1; $i <= $i_totalRow; $i++ ) {
            $o_dataClone = clone $o_dataEntity;
            $o_dataClone->unsetAttributes();

            //Loop columnName in table to get value from excel column, and put into array
            foreach ( $arr_HeaderIndexList as $s_columnName => $s_excelColumnIndex ) {
                $o_dataClone->$s_columnName = $arr_rowList[$i][$s_excelColumnIndex];
            }

            //Set into array List
            $arr_dataList[$i] = $o_dataClone;
        }//End foreach
        #EndRegion

        return $arr_dataList;
    }//End getDataFormExcel
}